<template>
    <div class="activity-list">
        <div class="filter-container">
            <el-input v-model="listQuery.title" placeholder="搜索活动标题" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.activityType" placeholder="活动类型" clearable style="width: 120px"
                class="filter-item">
                <el-option label="讲座" :value="1" />
                <el-option label="赛事" :value="2" />
                <el-option label="培训" :value="3" />
            </el-select>
            <el-select v-model="listQuery.status" placeholder="活动状态" clearable style="width: 120px" class="filter-item">
                <el-option label="报名中" :value="0" />
                <el-option label="进行中" :value="1" />
                <el-option label="已结束" :value="2" />
            </el-select>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="handleReset">
                重置
            </el-button>
        </div>

        <el-table v-loading="listLoading" height="500" :data="list" element-loading-text="Loading" border fit
            highlight-current-row style="width: 100%">
            <el-table-column align="center" label="ID" width="60">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="活动标题" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <router-link :to="'/activity/detail/' + scope.row.id" class="link-type">
                        <el-tooltip :content="scope.row.title" placement="top" :disabled="scope.row.title.length <= 20">
                            <span class="title-text">{{ scope.row.title }}</span>
                        </el-tooltip>
                    </router-link>
                </template>
            </el-table-column>
            <el-table-column label="类型" width="70" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.activityType)" size="small">
                        {{ getTypeLabel(scope.row.activityType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="发布者" width="90" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.publishName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="开始时间" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.startTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.endTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="报名截止" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.registrationDeadline }}</span>
                </template>
            </el-table-column>
            <el-table-column label="附件" width="100" align="center">
                <template slot-scope="scope">
                    <div v-if="scope.row.attachments && scope.row.attachments.length > 0">
                        <el-dropdown @command="handleDownloadAttachment" trigger="click">
                            <el-button type="text" size="mini" class="attachment-btn">
                                <i class="el-icon-paperclip"></i>
                                附件({{ scope.row.attachments.length }})
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                    :command="{ file, activity: scope.row }" class="attachment-item">
                                    <i :class="getFileIcon(file.name)" class="file-icon"></i>
                                    <span class="file-name">{{ file.name }}</span>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <span v-else class="no-attachment">无附件</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="70" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                        {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="报名状态" width="90" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getRegistrationStatusTagType(scope.row)" size="small">
                        {{ getRegistrationStatusLabel(scope.row) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="已报名/限制人数" width="120" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants || '∞' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="250" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleView(scope.row)">
                        查看详情
                    </el-button>
                    <!-- 报名按钮 -->
                    <el-button v-if="canRegister(scope.row)" size="mini" type="success"
                        @click="handleRegister(scope.row)">
                        报名
                    </el-button>
                    <!-- 已报名状态 -->
                    <el-button v-else-if="isRegistered(scope.row)" size="mini" type="info" disabled>
                        已报名
                    </el-button>
                    <!-- 取消报名按钮 -->
                    <el-button v-if="isRegistered(scope.row) && canCancelRegister(scope.row)" size="mini" type="warning"
                        @click="handleCancelRegister(scope.row)">
                        取消报名
                    </el-button>
                    <!-- 无法报名的状态显示 -->
                    <el-button v-else-if="!canRegister(scope.row) && !isRegistered(scope.row)" size="mini" type="info"
                        disabled>
                        {{ getRegistrationStatusText(scope.row) }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
            @pagination="getList" />
    </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getActivityList, registerActivity, cancelRegisterActivity } from '@/api/activity'
import Pagination from '@/components/Pagination'

export default {
    name: 'ActivityList',
    components: { Pagination },
    filters: {
        parseTime
    },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                pageNo: 1,
                pageSize: 20,
                title: undefined,
                activityType: undefined,
                status: undefined
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            try {
                this.listLoading = true
                const res = await getActivityList(this.listQuery)
                this.total = res.data.total || 0
                res.data.records.forEach(item => {
                    item.attachments = JSON.parse(item.attachmentUrl || '[]')
                })
                this.list = res.data.records || []
            } catch (error) {
                console.error(error)
            } finally {
                this.listLoading = false
            }
        },

        handleFilter() {
            this.listQuery.pageNo = 1
            this.getList()
        },
        handleReset() {
            this.listQuery = {
                pageNo: 1,
                pageSize: 20,
                title: undefined,
                activityType: undefined,
                status: undefined
            }
            this.getList()
        },
        handleView(row) {
            this.$router.push(`/activity/detail/${row.id}`)
        },
        async handleRegister(row) {
            try {
                await this.$confirm('确认报名参加此活动？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                // 调用报名API
                let res = await registerActivity(row.id)
                this.$message.success(res.data || '报名成功！')
                this.getList()
            } catch (error) {
                console.error(error)
            } finally {
                this.listLoading = false
            }

        },
        canRegister(row) {
            // 如果已经报名了，不能再次报名
            if (this.isRegistered(row)) {
                return false
            }

            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)

            // 活动状态必须是发布状态
            if (row.status !== 1) {
                return false
            }

            // 报名截止时间未到
            if (now > registrationDeadline) {
                console.log(`活动 ${row.title} 报名已截止`, {
                    now: now.toLocaleString(),
                    deadline: registrationDeadline.toLocaleString()
                })
                return false
            }

            // 活动未开始
            if (now >= startTime) {
                console.log(`活动 ${row.title} 已开始，无法报名`, {
                    now: now.toLocaleString(),
                    startTime: startTime.toLocaleString()
                })
                return false
            }

            // 检查是否已满员
            if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                return false
            }

            return true
        },
        // 获取报名状态文本
        getRegistrationStatusText(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 活动状态检查
            if (row.status !== 1) {
                return '活动未发布'
            }

            // 活动已结束
            if (now > endTime) {
                return '活动已结束'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return '活动进行中'
            }

            // 报名已截止
            if (now > registrationDeadline) {
                return '报名已截止'
            }

            // 已满员
            if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                return '已满员'
            }

            return '无法报名'
        },
        // 检查是否已报名
        isRegistered(row) {
            // 使用 isAnticipate 字段判断是否已参加活动
            // 0: 未参加, 1: 已参加
            return row.isAnticipate === 1
        },
        // 检查是否可以取消报名
        canCancelRegister(row) {
            const now = new Date()
            const startTime = new Date(row.startTime)

            // 活动未开始才能取消报名
            return now < startTime
        },
        // 处理取消报名
        async handleCancelRegister(row) {
            try {
                this.listLoading = true
                await this.$confirm('确认取消报名？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                // 调用取消报名API
                let res = await cancelRegisterActivity(row.id)
                this.$message.success(res.data || '取消报名成功！')
                this.getList()
            } catch (error) {
                console.error(error)
            } finally {
                this.listLoading = false
            }
        },
        handleDownloadAttachment(command) {
            const { file, activity } = command
            // 创建下载链接
            const link = document.createElement('a')
            link.href = file.url
            link.download = file.name
            link.target = '_blank'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.$message.success(`开始下载：${file.name}`)
        },
        getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase()
            const iconMap = {
                pdf: 'el-icon-document',
                doc: 'el-icon-document',
                docx: 'el-icon-document',
                xls: 'el-icon-s-grid',
                xlsx: 'el-icon-s-grid',
                ppt: 'el-icon-picture-outline',
                pptx: 'el-icon-picture-outline',
                txt: 'el-icon-document-copy',
                zip: 'el-icon-folder-opened',
                rar: 'el-icon-folder-opened'
            }
            return iconMap[ext] || 'el-icon-document'
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '讲座',
                2: '赛事',
                3: '培训',
                // 兼容字符串格式
                lecture: '讲座',
                competition: '赛事',
                training: '培训'
            }
            return typeMap[type] || type
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                // 兼容字符串格式
                lecture: 'primary',
                competition: 'success',
                training: 'warning'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                // 时间判断状态（筛选用）
                0: '报名中',
                1: '进行中',
                2: '已结束',
                // 活动发布状态（显示用）
                // 1: '发布',  // 与时间状态冲突，注释掉
                // 2: '结束',  // 与时间状态冲突，注释掉
                3: '取消',
                // 兼容字符串格式
                registering: '报名中',
                ongoing: '进行中',
                finished: '已结束'
            }
            return statusMap[status] || status
        },
        getStatusTagType(status) {
            const statusMap = {
                // 时间判断状态（筛选用）
                0: 'success',    // 报名中 - 绿色
                1: 'warning',    // 进行中 - 橙色
                2: 'info',       // 已结束 - 灰色
                // 活动发布状态（显示用）
                // 1: 'success', // 与时间状态冲突，注释掉
                // 2: 'warning', // 与时间状态冲突，注释掉
                3: 'danger',     // 取消 - 红色
                // 兼容字符串格式
                registering: 'success',
                ongoing: 'warning',
                finished: 'info'
            }
            return statusMap[status] || ''
        },
        // 获取报名状态标签文本
        getRegistrationStatusLabel(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态，直接返回对应状态
            if (row.status !== 1) {
                return this.getStatusLabel(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return '已结束'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return '进行中'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return '报名截止'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return '已满员'
                }
                return '报名中'
            }

            return '未知'
        },
        // 获取报名状态标签类型
        getRegistrationStatusTagType(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态
            if (row.status !== 1) {
                return this.getStatusTagType(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return 'info'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return 'success'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return 'warning'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return 'danger'
                }
                return 'primary'
            }

            return ''
        }
    }
}
</script>

<style lang="scss" scoped>
.activity-list {
    padding: 20px;
    width: 100%;
    overflow-x: auto;
}

.filter-container {
    padding-bottom: 10px;

    .filter-item {
        display: inline-block;
        vertical-align: middle;
        margin-bottom: 10px;
        margin-right: 10px;
    }
}

.link-type {
    color: #409EFF;
    text-decoration: none;
    display: block;

    &:hover {
        color: #66b1ff;
    }

    .title-text {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: top;
    }
}

.no-attachment {
    color: #c0c4cc;
    font-size: 12px;
}

.attachment-btn {
    color: #409EFF !important;
    font-size: 12px;
    padding: 2px 4px;

    &:hover {
        color: #66b1ff !important;
    }

    i {
        margin-right: 4px;
    }
}

::v-deep .el-dropdown-menu {
    .attachment-item {
        padding: 8px 12px;
        display: flex;
        align-items: center;

        .file-icon {
            margin-right: 8px;
            color: #409EFF;
            font-size: 14px;
        }

        .file-name {
            font-size: 12px;
            color: #606266;
        }

        &:hover {
            background-color: #ecf5ff;

            .file-name {
                color: #409EFF;
            }
        }
    }
}
</style>
